package com.carl.leetcode.backtracking;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by carlXie on 2016/3/14.
 */
public class GenerateParentheses {

    public static List<String> generateParenthesis(int n) {
        List<String> resultList = new ArrayList<String>();
        gp(resultList, "", 0, n);

        return resultList;
    }

    /**
     *
     * @param list 存储结果的集合
     * @param str 当前的字符串
     * @param unCover   当前字符串中没有被覆盖的"("的数量
     * @param left  剩下没有使用的"("的数量
     */
    private static void gp(List<String> list, String str, int unCover, int left) {
        if(left == 0) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < unCover; i++) {
                sb.append(")");
            }
            list.add(str + sb.toString());
            return;
        }

        if(unCover == 0) {
            gp(list, str + "(", 1, left - 1);
        } else {
            gp(list, str + "(", unCover + 1, left - 1);
            gp(list, str + ")", unCover - 1, left);
        }
    }

    public static void main(String[] args) {
        List<String> resultList = generateParenthesis(0);
        for (String str: resultList) {
            System.out.println(str);
        }
    }

}
